package com.control.qct.businesssteward.utils;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.widget.Toast;

import com.control.qct.businesssteward.base.BaseActivity;
import com.control.qct.businesssteward.base.BaseFragment;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CaptureFragment;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import java.io.ByteArrayOutputStream;

import static android.app.Activity.RESULT_OK;

/**
 * 二维码封装类
 * Created by Administrator on 2017/12/20 0020.
 */

public class CustomCodeUtils {
    private static CustomCodeUtils mCustomCodeUtils;
    private Context mContext;
    public static final int REQUEST_CODE = 0x001001;
    public static final int REQUEST_IMAGE = 0x001002;
    public static final int REQUEST_CAMERA = 0x001003;

    private CustomCodeUtils(Context context) {
        this.mContext = context;
        ZXingLibrary.initDisplayOpinion(mContext);
    }

    public static CustomCodeUtils getInstance(Context context) {
        if (mCustomCodeUtils == null) {
            mCustomCodeUtils = new CustomCodeUtils(context);
        }
        return mCustomCodeUtils;
    }

    /**
     * 调转到二维码扫描界面
     *
     * @param fragment
     */
    public void startToCaptureActivity(BaseFragment fragment) {
        fragment.startActivityForResult(CaptureActivity.class, REQUEST_CODE);
    }

    /**
     * 调转到二维码扫描界面
     *
     * @param activity
     */
    public void startToCaptureActivity(BaseActivity activity) {
        activity.startActivityForResult(CaptureActivity.class, REQUEST_CODE);
    }

    /**
     * 处理二维码扫描结果
     */
    public void onCallBackListener(int requestCode, Intent data, ICallbackListener listener) {
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    listener.onCallbackListener(result);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(mContext, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    /**
     * 打开相册
     *
     * @param activity
     */
    public void openPicture(Activity activity) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        activity.startActivityForResult(intent, REQUEST_IMAGE);
    }

    public void openPictureCallBack(int requestCode, Intent data) {
        if (requestCode == REQUEST_IMAGE) {
            if (data != null) {
                Uri uri = data.getData();
                ContentResolver cr = mContext.getContentResolver();
                try {
                    Bitmap mBitmap = MediaStore.Images.Media.getBitmap(cr, uri);//显得到bitmap图片

                    CodeUtils.analyzeBitmap(convertIconToString(mBitmap), new CodeUtils.AnalyzeCallback() {
                        @Override
                        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
                            Toast.makeText(mContext, "解析结果:" + result, Toast.LENGTH_LONG).show();
                        }

                        @Override
                        public void onAnalyzeFailed() {
                            Toast.makeText(mContext, "解析二维码失败", Toast.LENGTH_LONG).show();
                        }
                    });

                    if (mBitmap != null) {
                        mBitmap.recycle();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 为二维码扫描界面设置定制化界面
     *
     * @param activity
     * @param layoutId
     * @param viewId
     */
    public void replaceCodeCapture(AppCompatActivity activity, int layoutId, int viewId) {
        CaptureFragment captureFragment = new CaptureFragment();
        CodeUtils.setFragmentArgs(captureFragment, layoutId);
        captureFragment.setAnalyzeCallback(getAnalyzeCallback(activity));
        /**
         * 替换我们的扫描控件
         */
        activity.getSupportFragmentManager().beginTransaction().replace(viewId, captureFragment).commit();
    }

    /**
     * 二维码解析回调函数
     */

    public CodeUtils.AnalyzeCallback getAnalyzeCallback(final AppCompatActivity activity) {
        CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
            @Override
            public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
                Intent resultIntent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_SUCCESS);
                bundle.putString(CodeUtils.RESULT_STRING, result);
                resultIntent.putExtras(bundle);
                activity.setResult(RESULT_OK, resultIntent);
                activity.finish();
            }

            @Override
            public void onAnalyzeFailed() {
                Intent resultIntent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_FAILED);
                bundle.putString(CodeUtils.RESULT_STRING, "");
                resultIntent.putExtras(bundle);
                activity.setResult(RESULT_OK, resultIntent);
                activity.finish();
            }
        };
        return analyzeCallback;
    }

    /**
     * 生成带logo的二维码
     *
     * @param content
     * @param imageId
     */
    public Bitmap createLogoCode(String content, int imageId) {
        return CodeUtils.createImage(content, 400, 400, BitmapFactory.decodeResource(mContext.getResources(), imageId));
    }

    /**
     * 生成不带logo的二维码
     *
     * @param content
     */
    public Bitmap createCode(String content) {
        return CodeUtils.createImage(content, 400, 400, null);
    }

    /**
     * 打开闪光灯
     */
    public void openLight() {
        CodeUtils.isLightEnable(true);
    }


    /**
     * 关闭闪光灯
     */
    public void closeLight() {
        CodeUtils.isLightEnable(false);
    }


    /**
     * 图片转成string
     *
     * @param bitmap
     * @return
     */
    public String convertIconToString(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] appicon = baos.toByteArray();// 转为byte数组
        return Base64.encodeToString(appicon, Base64.DEFAULT);

    }

    /**
     * string转成bitmap
     *
     * @param st
     */
    public Bitmap convertStringToIcon(String st) {
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray;
            bitmapArray = Base64.decode(st, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
            return bitmap;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 运行时权限--打开相机
     * @param context
     */
    public static void setSelfPermission(BaseActivity context) {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager
                .PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA);
        }
    }

    /**
     * 二维码扫描结果返回
     */
    public interface ICallbackListener {
        void onCallbackListener(String result);
    }
}
